
package com.hanxiaozhang.http.util;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 功能描述: <br>
 * 〈Yaml工具类〉
 *
 * @Author:hanxiaozhang
 * @Date: 2022/4/25
 */
public class YamlUtil {

    private static final Logger logger = Logger.getLogger(YamlUtil.class);

    public static Map parse(File file, String nodes) {
        Yaml yaml = new Yaml();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.error("yaml parse error is [{}]", e);
            throw new RuntimeException(e.getMessage());
        }
        Map<String, LinkedHashMap> map = (LinkedHashMap) yaml.load(inputStream);
        return parse(map, nodes.split("\\."));
    }

    public static Map parse(InputStream inputStream, String nodes) {
        Yaml yaml = new Yaml();
        Map<String, LinkedHashMap> map = (LinkedHashMap) yaml.load(inputStream);
        return parse(map, nodes.split("\\."));
    }

    private static Map parse(Map<String, LinkedHashMap> map, String[] nodes) {
        Map nm = map.get(nodes[0]);
        if (nodes.length == 1) {
            return nm;
        }
        String[] ns = new String[nodes.length - 1];
        System.arraycopy(nodes, 1, ns, 0, ns.length);
        return parse(nm, ns);
    }

}
